import { Component, ViewChild } from '@angular/core';
import { NavController, NavParams, Events, Platform } from 'ionic-angular';
import { EleDetailPage } from '../elevator-detail/elevator-detail';
import { Storage } from '@ionic/storage';
import { SignatrueComponent } from '../../components/signatrueComponent/signatrue.Component';

import { appConfig } from '../../providers/config';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/observable/from';
import { HttpService } from './../../providers/http.service';
import { CommonFunc } from './../../providers/commonFunc';
import { Refresher } from './../../pages/refresher/refresher';
import { InformDetail } from './../../pages/refresher/inform-detail/inform-detail';
import { NoticeDetail } from './../../pages/refresher/notice-detail/notice-detail';
import { SignPage } from '../sign/sign';
import { MaintInfo } from './maint-info/maint-info';
import { UsedInfo } from './used-info/used-info';
import { ApplyRepairDetailPage } from '../repair-apply-detail/apply-repair-detail';
import { SecurityManagePage } from '../supervision/security-manage/security-manage';
import { Slides } from 'ionic-angular';
import { RescuDrillPage } from '../rescue-drill/rescue-drill';
import { QRScanner } from '@ionic-native/qr-scanner';
import { ScanPage } from '../scan/scan';
import { PlanList } from '../supervision/plan-list/plan-list';
import { MyCachePage } from '../my-cache/my-cache';
import {FinishCheckList} from '../maintenance/finish-check-list/finish-check-list';
// import VConsole from 'vconsole'
import {RepairListPage} from "../used-repair/repair-list/repair-list";
import {maintenanceBeforePage} from "../maince-type/maintenance-before/maintenanceBefore";
import {MaintUserAddPage} from "../maint-user-add/maintUserAdd";
import {RepairDetailPage} from "../used-repair/repair-detail/repair-detail";

// const  vConsole = new VConsole();

@Component({
  templateUrl: 'home.html',
  providers: [SignatrueComponent]
})
export class HomePage {
  @ViewChild(Slides)
  slides: Slides;
  private isPassenger: boolean = false;
  config = appConfig;
  workType: any;
  //通知列表
  private noticeList: any = [];
  //资讯列表
  private infromList: any = [];

  private isUsedUser = false;
  private isMaintUser = false;
  private imgUrl = '';
  private imgUrl1 = '';
  private imgUrl2 = '';
  private imgUrl3 = '';
  noticeTotal = '0';
  gxhs = '';
  isBoss = false;
  partyType = '';
  partyId = '';
  roleId = '';
  empiric = 0;
  grade = '';
  user: any;
  private slideList: any = [];
  private borderIdx: any;
  appType:string = "";
  mark: 0;
  constructor(
    private navCtrl: NavController,
    private storage: Storage,
    private navParams: NavParams,
    private httpService: HttpService,
    private commonFunc: CommonFunc,
    private qrScanner: QRScanner,
    private events: Events,
    private platform: Platform
  ) {
    this.isPassenger = navParams.get('isPassenger');
    // this.events.subscribe('update:address', data => {
    //   let address = data.value.replace(/^bitcoin(cash)?:/, '');
    //   let datas: Array<string> = address.split('?')[1].split('&');
    //   let elevatorId = datas[0].split('=')[1];
    //   let elevatorType = datas[1].split('=')[1];
    //   let elevatorNum = datas[2].split('=')[1];
    //   this.navCtrl.push(EleDetailPage, {
    //     elevatorNum: elevatorNum,
    //     elevatorType: elevatorType,
    //     elevatorId: elevatorId,
    //     isPassenger: this.isPassenger,
    //     workType: this.workType
    //   });
    // });
  }

  ionViewWillEnter() {
    if (!this.isPassenger) {
      setTimeout(() => {
        this.storage.get('user').then(val => {
            // 通过用户名获取用户名积分
            if (val != null && val.id != null) {
                this.httpService.getMarkById({"id":val.id}).subscribe(data => {
                    if (data.status == 200) {
                        if (data.data.mark != null && data.data.mark > 0) {
                            console.log("~~~~~~~~~~~~");
                            this.mark = data.data.mark;
                            console.log(this.mark);
                            console.log("~~~~~~~~~~~~");
                        }
                    }
                });
            }
            /*if (val.mark != null && val.mark > 0) {
                this.mark = val.mark;
            }*/
          this.user = val;
          this.partyType = val.partyType;
          this.roleId = val.roleId;
          this.partyId = val.partyId;

          //alert(JSON.stringify(val));
          //获取通知和质询的列表
          if (val.partyType == 1) {
            this.isMaintUser = true;
            this.imgUrl = 'assets/banner1.png';
            this.slideList.push({ urlpath: this.imgUrl, operateType: '0' });
            this.appType = "维保单位";
          } else if (val.partyType == 2) {
            this.isUsedUser = true;
            this.imgUrl = 'assets/banner2.png';
            this.slideList.push({ urlpath: this.imgUrl, operateType: '0' });
            this.appType = "使用单位";
          }else if(val.partyType == 3){
            this.appType = "检测单位";
          } else if (val.partyType == 4) {
            this.isBoss = true;
            this.imgUrl1 = 'assets/banner31.png';
            this.imgUrl2 = 'assets/banner21.png';
            this.imgUrl3 = 'assets/banner11.png';
            this.slideList.push({ urlpath: this.imgUrl1, operateType: '0' });
            this.slideList.push({ urlpath: this.imgUrl2, operateType: '0' });
            this.slideList.push({ urlpath: this.imgUrl3, operateType: '0' });
            this.appType = "监管单位";
          }
          let currentUserId = val.id;
          let noticeParam = {
            isRead: '0',
            pageSize: 3,
            currentPage: 1,
            currentUserId: currentUserId
          };
          let infromParam = {
            pageSize: 3,
            currentPage: 1,
            createPartyId: val.partyId,
            parentId: val.partyParentId
          };
          let observable = Observable.forkJoin([
            //查询通知
            Observable.from(this.httpService.noticeQueryList(noticeParam)), //查询咨询
            Observable.from(this.httpService.informationQueryList(infromParam)), //查询轮播图
            Observable.from(
              this.httpService.advertiseQuery({
                discription: '手机端'
              })
            )
          ]);
          observable.subscribe(data => {
            if (data[2].data) {
              if (data[2].data.list && data[2].data.list.length > 0) {
                data[2].data.list.forEach(advertisement => {
                  advertisement.urlpath = this.config.IP_URL + '/' + this.config.API.getUpload + advertisement.url
                  this.slideList.push(advertisement);
                });
              }
              if (data[2].data.discription) {
                this.gxhs = data[2].data.discription;
              }
            }

            for (let d in data) {
              let item = data[d].status != 200;
              if (item) {
                let toast = this.commonFunc.showInsideErrorToast(data);
                toast.present();
                return;
              }
            }
            this.noticeList = data[0].data.list;
            this.noticeTotal = data[0].data.total;
            this.infromList = data[1].data.list;
          });

          //查积分
          if (val.partyType == '1' || val.partyType == '2') {
            let param = {
              type: '',
              userId: ''
            }
            param.type = val.partyType;
            param.userId = val.partyId;
            if (val.roleName == '电梯维保人员') {
              param.type = '4';
              param.userId = val.id;
            }
            if (val.roleName == '电梯安全管理员') {
              param.type = '3';
              param.userId = val.id;
            }

            this.httpService.queryEmpiric(param).subscribe(data => {
              console.log(data)
              if (data.status == '200') {
                this.empiric = data.data.empiricValue;
                this.grade = data.data.grade;
              }
            });

          }
        });



      }, 300);
    }
  }
  /**
   * 扫描二维码
   */
  doScan(data) {
    // this.navCtrl.push(EleDetailPage, {
    //   elevatorNum: '31203201142017020002',
    //   elevatorType: '1',
    //   elevatorId: '3',
    //   isPassenger: this.isPassenger,
    //   workType: data
    // });

    // let barcodeScannerOptions: BarcodeScannerOptions = {
    //   showTorchButton: true,
    //   torchOn: false,
    //   showFlipCameraButton: true
    // };
    // this.barcodeScanner.scan(barcodeScannerOptions).then(
    //   barcodeData => {
    //     let url = barcodeData.text;
    //     let datas: Array<string> = url.split('?')[1].split('&');
    //     let elevatorId = datas[0].split('=')[1];
    //     let elevatorType = datas[1].split('=')[1];
    //     let elevatorNum = datas[2].split('=')[1];

    //     this.navCtrl.push(EleDetailPage, {
    //       elevatorNum: elevatorNum,
    //       elevatorType: elevatorType,
    //       elevatorId: elevatorId,
    //       isPassenger: this.isPassenger,
    //       workType: data
    //     });
    //   },
    //   err => {}
    // );
    this.workType = data;
      if (this.workType == "11") {
          this.navCtrl.push(RepairListPage);
      } else {
          this.navCtrl.push(ScanPage, {workType: this.workType});
      }


    // this.qrScanner
    //   .prepare()
    //   .then((status: QRScannerStatus) => {
    //     if (status.authorized) {
    //       // camera permission was granted

    //       // start scanning

    //       let scanSub = this.qrScanner.scan().subscribe((text: string) => {
    //         // console.log('Scanned something', text);
    //         let url = text;
    //         let datas: Array<string> = url.split('?')[1].split('&');
    //         let elevatorId = datas[0].split('=')[1];
    //         let elevatorType = datas[1].split('=')[1];
    //         let elevatorNum = datas[2].split('=')[1];
    //         this.qrScanner.hide(); // hide camera preview
    //         scanSub.unsubscribe(); // stop scanning
    //         this.navCtrl.push(EleDetailPage, {
    //           elevatorNum: elevatorNum,
    //           elevatorType: elevatorType,
    //           elevatorId: elevatorId,
    //           isPassenger: this.isPassenger,
    //           workType: data
    //         });
    //       });
    //       this.qrScanner.show();
    //     } else if (status.denied) {
    //       this.qrScanner.openSettings();
    //       // camera permission was permanently denied
    //       // you must use QRScanner.openSettings() method to guide the user to the settings page
    //       // then they can grant the permission from there
    //     } else {
    //       // permission was denied, but not permanently. You can ask for permission again at a later time.
    //     }
    //   })
    //   .catch((e: any) => console.log('Error is', e));
  }

  more(param) {
    this.navCtrl.push(Refresher, { param: param });
  }

  cache() {
    this.navCtrl.push(MyCachePage);
  }
  //查看通知的详情
  noticeDetail(param, idx) {
    this.borderIdx = idx;
    if(param.elevatoriMonId != null && param.elevatoriType == "8" && param.isRead == "0") {
       this.navCtrl.push(RepairDetailPage, {repairInfoId: param.elevatoriMonId, params: param, id: param.id});
       return;
    }
    if (param.elevatoriType == '5') {
      this.navCtrl.push(ApplyRepairDetailPage, {
        id: param.elevatoriMonId,
        noticeId: param.id
      });
      return;
    }
    if (param.elevatoriType == '6') { //监督检查
      this.navCtrl.push(NoticeDetail, { id: param.id });
      return;
    }
    //判断是否是电梯维保的信息elevatoriMonId
    if (param.elevatoriMonId != null && param.elevatoriMonId.length > 0) {
      this.navCtrl.push(SignPage, { ElevaType: 'notice', params: param });
    } else {
      this.navCtrl.push(NoticeDetail, { id: param.id });
    }
  }
  //查看咨询的详情
  infromDetail(param) {
    this.navCtrl.push(InformDetail, { id: param.id });
  }

  toAqzs(l) {
    if (l.operateType == '0') {
      if (this.isMaintUser) {
        this.navCtrl.push(MaintInfo);
      }
      if (this.isUsedUser) {
        this.navCtrl.push(UsedInfo);
      }
    }
    if (l.operateType == '2') {
      this.commonFunc.openUrl(l.linkUrl)
    }
    if (l.operateType == '3') {
      this.navCtrl.push(InformDetail, { id: l.infoId });
    }
    if (l.operateType == '5') {
      this.httpService.downloadApp(l.linkUrl);
    }
    if (l.operateType == '4') {
      this.navCtrl.push(l.linkUrl);
    }
    if (l.operateType == '6') {
      this.commonFunc.toappstore(l.linkUrl);
    }

  }

  doCheck() {
    this.navCtrl.push(SecurityManagePage);
  }

  ionViewDidEnter() {
    //修复轮播手动滑动后不能自动轮播问题
    if (this.slides) {
      this.slides.autoplayDisableOnInteraction = false;
    }
  }

  doDrill() {
    this.navCtrl.push(RescuDrillPage);
  }

  toPlanList(type) {
    this.navCtrl.push(PlanList, { type: type });
  }

  // 维保完成检查列表
  toFinish(){
      this.navCtrl.push(FinishCheckList);
  }

  logout() {
    this.platform.exitApp();
  }
}
